#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
API密钥配置工具
帮助用户快速配置OpenAI API密钥
"""

import os
import json
from pathlib import Path

def setup_api_key():
    """配置API密钥"""
    print("OpenAI API密钥配置工具")
    print("=" * 30)

    print("\n获取API密钥的步骤：")
    print("1. 访问 https://platform.openai.com/api-keys")
    print("2. 登录您的OpenAI账户")
    print("3. 点击 'Create new secret key'")
    print("4. 输入密钥名称并创建")
    print("5. 复制生成的密钥")

    # 获取用户输入
    api_key = input("\n请粘贴您的OpenAI API密钥: ").strip()

    if not api_key:
        print("未输入密钥，配置取消")
        return False

    # 验证密钥格式
    if not api_key.startswith('sk-'):
        print("警告: API密钥通常以'sk-'开头")

    # 询问保存方式
    print("\n选择保存方式：")
    print("1. 保存到config.json文件（推荐）")
    print("2. 设置为环境变量（仅当前会话）")
    print("3. 同时使用两种方式")

    choice = input("\n请选择 (1-3): ").strip()

    project_root = Path(__file__).parent
    config_file = project_root / "config.json"

    if choice == "1":
        # 保存到配置文件
        config = {}
        if config_file.exists():
            try:
                with open(config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
            except:
                pass

        config['openai_api_key'] = api_key
        config['model'] = 'gpt-3.5-turbo'
        config['temperature'] = 0.1

        with open(config_file, 'w', encoding='utf-8') as f:
            json.dump(config, f, indent=2, ensure_ascii=False)

        print(f"\n✓ API密钥已保存到 {config_file}")
        return True

    elif choice == "2":
        # 设置环境变量
        os.environ['OPENAI_API_KEY'] = api_key
        print("\n✓ API密钥已设置为环境变量")
        print("注意：此设置仅在当前命令行会话中有效")
        return True

    elif choice == "3":
        # 同时使用两种方式
        # 保存到配置文件
        config = {}
        if config_file.exists():
            try:
                with open(config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
            except:
                pass

        config['openai_api_key'] = api_key
        config['model'] = 'gpt-3.5-turbo'
        config['temperature'] = 0.1

        with open(config_file, 'w', encoding='utf-8') as f:
            json.dump(config, f, indent=2, ensure_ascii=False)

        # 设置环境变量
        os.environ['OPENAI_API_KEY'] = api_key

        print(f"\n✓ API密钥已保存到 {config_file}")
        print("✓ API密钥已设置为环境变量")
        return True

    else:
        print("无效选择，配置取消")
        return False

def check_current_config():
    """检查当前配置"""
    print("\n检查当前配置...")

    # 检查环境变量
    env_key = os.getenv("OPENAI_API_KEY")
    if env_key:
        print("✓ 环境变量中已配置API密钥")
    else:
        print("✗ 环境变量中未配置API密钥")

    # 检查配置文件
    project_root = Path(__file__).parent
    config_file = project_root / "config.json"

    if config_file.exists():
        try:
            with open(config_file, 'r', encoding='utf-8') as f:
                config = json.load(f)
                if 'openai_api_key' in config:
                    print("✓ config.json中已配置API密钥")
                else:
                    print("✗ config.json中未配置API密钥")
        except:
            print("✗ config.json文件格式错误")
    else:
        print("✗ config.json文件不存在")

def main():
    """主函数"""
    check_current_config()

    print("\n" + "=" * 40)
    print("1. 配置新的API密钥")
    print("2. 重新检查配置")
    print("3. 退出")

    choice = input("\n请选择 (1-3): ").strip()

    if choice == "1":
        if setup_api_key():
            print("\n配置完成！现在可以启动智能助手了")
            print("运行命令: python start_simple.py")
        else:
            print("\n配置失败")
    elif choice == "2":
        main()
    elif choice == "3":
        print("再见！")
    else:
        print("无效选择")
        main()

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n程序被用户中断")
    except Exception as e:
        print(f"程序异常: {e}")